package com.spring.sunflower.userinfo

import android.content.ContentValues
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.view.View
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import com.alibaba.sdk.android.oss.model.PutObjectRequest
import com.bumptech.glide.Glide
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.spring.sunflower.R
import com.spring.sunflower.base.BaseActivity
import com.spring.sunflower.bean.STSCertBean
import com.spring.sunflower.common.CommonContract
import com.spring.sunflower.common.FileUploadCallback
import com.spring.sunflower.constant.Constant
import com.spring.sunflower.event.ImageSendSuccessEvent
import com.spring.sunflower.util.AliUploadUtils
import kotlinx.android.synthetic.main.activity_auth_real.*

import com.lxj.xpopup.XPopup
import com.makeramen.roundedimageview.RoundedImageView
import com.spring.sunflower.dialog.OnPermissionIntroClickListener
import com.spring.sunflower.util.AppUtils
import com.spring.sunflower.util.PathUtils
import java.io.File


/**
 * Created by Kevin on 2021/8/15<br/>
 *
 * Describe:<br/>
 */
class AuthRealActivity : BaseActivity<AuthRealPresenter>(), CommonContract.AuthRealView {
    private var llUploadPic: LinearLayout? = null
    private var rivAvatar: RoundedImageView? = null
    private var tvDone: TextView? = null
    private var progressBar: ProgressBar? = null
    private var aliUploadUtils: AliUploadUtils? = null
    private var keyID = ""
    private var keySecret = ""
    private var securityToken = ""
    private var avatarUrl = ""
    private var authAvatarUrl = ""
    private var fileName = ""
    private var mFilePath = ""

    override fun initView() {
        tvTitle.text = "真人认证"
        avatarUrl = getField(Constant.KEY_PHOTO, "")
        llUploadPic = findViewById(R.id.llUploadPic)
        rivAvatar = findViewById(R.id.rivAvatar)
        tvDone = findViewById(R.id.tvDone)
        progressBar = findViewById(R.id.pbProgress)
        mPresenter.getSTSCert()
        Glide.with(this)
            .load(avatarUrl)
            .placeholder(R.drawable.ic_placeholder)
            .into(rivAvatar!!)
        llUploadPic!!.setOnClickListener {
            checkOpenGallery(this, true)
        }
        val dialog = AuthRealBottomDialog(this)
        dialog.setOnDoneClickListener(object : AuthRealBottomDialog.OnDoneClickListener {
            override fun onDoneClick() {
                val grant = getField(Constant.AUTH_REAL_GRANT, false)
                if (grant) {
                    takePhoto()
                } else {
                    val intent =
                        Intent(this@AuthRealActivity, AuthRealGrantActivity::class.java)
                    startActivityForResult(intent, Constant.REQUEST_CODE_AUTH_REAL_GRANT)
                }
            }

        })
        tvDone!!.setOnClickListener {
//            Intent(this,)
            XPopup.Builder(this)
                .enableDrag(false)
                .asCustom(dialog)
                .show()
        }
    }

    override fun getLayoutID(): Int = R.layout.activity_auth_real

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> if (data != null) {
                    val localMedia = PictureSelector.obtainMultipleResult(data)
                    val localMedia1 = localMedia[0]
                    var path = localMedia1.path
                    //                        showToast("path=" + path);
                    val cropImageWidth = localMedia1.cropImageWidth
                    val cropImageHeight = localMedia1.cropImageHeight
                    val width = localMedia1.width
                    val height = localMedia1.height
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                        path = PathUtils.getPath(this@AuthRealActivity, Uri.parse(path))
                    }
                    if (localMedia1.isCut) {
                        path = localMedia1.cutPath
                    }
                    if (aliUploadUtils != null) {
                        progressBar!!.visibility = View.VISIBLE
                        aliUploadUtils!!.upLoadFile(path, object : FileUploadCallback<Any?, Any?> {
                            override fun onFailure(str: String) {
                                progressBar!!.visibility = View.GONE
                                showToast("上传失败,请稍后重试")
                            }

                            override fun onSuccess(paramRequestString: Any?, filePath: String) {
//                                    showToast("filePath=" + filePath);
                                showToast("上传成功")
                                Glide.with(this@AuthRealActivity)
                                    .load(filePath)
                                    .placeholder(R.drawable.ic_placeholder)
                                    .into(rivAvatar!!)
                                avatarUrl = filePath
                                val event = ImageSendSuccessEvent()
//                                event.imgUrl = filePath
//                                event.width = width
//                                event.height = height
//                                imageSendSuccess(event)
                            }

                            override fun onProgress(
                                request: PutObjectRequest,
                                currentSize: Long,
                                totalSize: Long
                            ) {
                                printD("progress=" + currentSize * 1.0 / totalSize)
                                if (currentSize * 10 / totalSize == 1L) {
                                    progressBar!!.visibility = View.GONE
                                }
                            }
                        })
                    }
                }
                Constant.REQUEST_CODE_AUTH_REAL_GRANT -> {
                    val grant = getField(Constant.AUTH_REAL_GRANT, false)
                    if (grant) {
                        takePhoto()
                    }
                }
                Constant.REQUEST_CODE_AUTH_REAL_SHOT -> {
                    showLoading()
                    aliUploadUtils!!.upLoadFile(mFilePath, object : FileUploadCallback<Any?, Any?> {
                        override fun onFailure(str: String) {
                            hideLoading()
//                            progressBar!!.visibility = View.GONE
                            showToast("上传失败,请稍后重试")
                        }

                        override fun onSuccess(paramRequestString: Any?, filePath: String) {
//                            showToast("filePath=" + filePath);
//                            hideLoading()
                            if (TextUtils.isEmpty(filePath)) {
                                hideLoading()
                                return
                            }
                            authAvatarUrl = filePath
                            mPresenter.requestRealAuth(authAvatarUrl, avatarUrl)
                        }

                        override fun onProgress(
                            request: PutObjectRequest,
                            currentSize: Long,
                            totalSize: Long
                        ) {
                            printD("progress=" + currentSize * 1.0 / totalSize)
                            if (currentSize * 10 / totalSize == 1L) {
//                                progressBar!!.visibility = View.GONE
                            }
                        }
                    })
                }
                Constant.REQUEST_CODE_AUTH_REAL_RESULT_BACK -> {
                    onBackPressed()
                }
            }
        }
    }

    override fun setPresenter(): AuthRealPresenter = AuthRealPresenter(this)

    override fun loadSTSCert(data: STSCertBean.DatasBean?) {
        keyID = data!!.accessKeyId
        keySecret = data.accessKeySecret
        securityToken = data.securityToken
        saveField(Constant.STS_KEY_ID, keyID)
        saveField(Constant.STS_KEY_SECRET, keySecret)
        saveField(Constant.STS_SECURITY_TOKEN, securityToken)
        aliUploadUtils = AliUploadUtils.getInstance(keyID, keySecret, securityToken)
    }

    override fun authRealSuccess() {
        hideLoading()
        val intent = Intent(this, AuthRealResultActivity::class.java)
        intent.putExtra("authAvatar", authAvatarUrl)
        intent.putExtra("currentAvatar", avatarUrl)
        intent.putExtra("authResult", true)
        startActivityForResult(intent, Constant.REQUEST_CODE_AUTH_REAL_RESULT_BACK)
    }

    override fun authRealFailed() {
        hideLoading()
        val intent = Intent(this, AuthRealResultActivity::class.java)
        intent.putExtra("authAvatar", authAvatarUrl)
        intent.putExtra("currentAvatar", avatarUrl)
        intent.putExtra("authResult", false)
        startActivity(intent)
        startActivityForResult(intent, Constant.REQUEST_CODE_AUTH_REAL_RESULT_BACK)
    }

    fun takePhoto() {
        if (!XXPermissions.isGranted(this, Permission.CAMERA) && !XXPermissions.isGranted(
                this,
                Permission.WRITE_EXTERNAL_STORAGE
            )
        ) {
            showPermissionIntroDialog(
                arrayOf(
                    getString(R.string.permission_camera_title),
                    getString(R.string.permission_storate_title),
                ),
                arrayOf(
//                    getString(R.string.permission_audio_desc),
//                    getString(R.string.permission_camera_desc)
                    "您当前正在进行真人认证，该功能需要打开手机摄像头才能使用，如拒绝该权限，将无法使用该功能",
                    "真人认证需要存储权限才能进行认证，如拒绝该权限，将无法使用该功能"
                ),
                object : OnPermissionIntroClickListener {
                    override fun onClickOK() {
                        XXPermissions.with(this@AuthRealActivity)
                            .permission(Permission.CAMERA, Permission.WRITE_EXTERNAL_STORAGE)
                            .request(object : OnPermissionCallback {
                                override fun onGranted(permissions: List<String>, all: Boolean) {
                                    if (all) {
                                        takePhotoAction()
                                    } else {
                                        showToast("无法进行真人认证")
                                    }
                                }

                                override fun onDenied(permissions: List<String>, never: Boolean) {
                                    showToast("无法进行真人认证")
                                }
                            })
                    }

                    override fun onClickCancel() {
                        showToast("无法进行真人认证")
                    }
                })
        } else if (XXPermissions.isGranted(
                this,
                Permission.CAMERA
            ) and !XXPermissions.isGranted(this, Permission.WRITE_EXTERNAL_STORAGE)
        ) {
            showPermissionIntroDialog(
                arrayOf(
                    getString(R.string.permission_storate_title),
                ),
                arrayOf(
//                    getString(R.string.permission_audio_desc),
//                    getString(R.string.permission_camera_desc)
                    "真人认证需要存储权限才能进行认证，如拒绝该权限，将无法使用该功能"
                ),
                object : OnPermissionIntroClickListener {
                    override fun onClickOK() {
                        XXPermissions.with(this@AuthRealActivity)
                            .permission(Permission.WRITE_EXTERNAL_STORAGE)
                            .request(object : OnPermissionCallback {
                                override fun onGranted(permissions: List<String>, all: Boolean) {
                                    if (all) {
                                        takePhotoAction()
                                    } else {
                                        showToast("无法进行真人认证")
                                    }
                                }

                                override fun onDenied(permissions: List<String>, never: Boolean) {
                                    showToast("无法进行真人认证")
                                }
                            })
                    }

                    override fun onClickCancel() {
                        showToast("无法进行真人认证")
                    }
                })
        } else if (XXPermissions.isGranted(
                this,
                Permission.WRITE_EXTERNAL_STORAGE
            ) and !XXPermissions.isGranted(this, Permission.CAMERA)
        ) {
            showPermissionIntroDialog(
                arrayOf(
                    getString(R.string.permission_camera_title),
                ),
                arrayOf(
//                    getString(R.string.permission_audio_desc),
//                    getString(R.string.permission_camera_desc)
                    "您当前正在进行真人认证，该功能需要打开手机摄像头才能使用，如拒绝该权限，将无法使用该功能",
                ),
                object : OnPermissionIntroClickListener {
                    override fun onClickOK() {
                        XXPermissions.with(this@AuthRealActivity)
                            .permission(Permission.CAMERA)
                            .request(object : OnPermissionCallback {
                                override fun onGranted(permissions: List<String>, all: Boolean) {
                                    if (all) {
                                        takePhotoAction()
                                    } else {
                                        showToast("无法进行真人认证")
                                    }
                                }

                                override fun onDenied(permissions: List<String>, never: Boolean) {
                                    showToast("无法进行真人认证")
                                }
                            })
                    }

                    override fun onClickCancel() {
                        showToast("无法进行真人认证")
                    }
                })
        } else {
            takePhotoAction()
        }
    }

    private fun takePhotoAction() {
        val fileDir =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) File(
                Environment.getExternalStorageDirectory(),
                "DCIM/${AppUtils.getAppName(this)}"
            ) else File(
                Environment.getExternalStorageDirectory(),
                "${AppUtils.getAppName(this)}"
            )
        printD("fileDir=${fileDir.absolutePath},name=${fileDir.name},exists=${fileDir.exists()},Environment.getExternalStorageDirectory()=${Environment.getExternalStorageDirectory().absolutePath}")
        if (!fileDir.exists()) {
            fileDir.mkdir()
        }
        fileName = "IMG_" + System.currentTimeMillis() + ".jpg"
        mFilePath = fileDir.absolutePath + "/" + fileName
        var uri: Uri? = null
        val contentValues = ContentValues()
        //设置文件名
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            //            mFilePath = fileDir.absolutePath + "/${AppUtils.getAppName(this)}/${fileName}"
            printD("QQ mFilePath=${mFilePath}")
            contentValues.put(
                MediaStore.Images.Media.RELATIVE_PATH,
                "DCIM/${AppUtils.getAppName(this)}"
            )
        } else {
            contentValues.put(MediaStore.Images.Media.DATA, mFilePath)
        }
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
        uri =
            contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
        //        uri = createImageUri()
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) // 启动系统相机
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri!!)
        startActivityForResult(intent, Constant.REQUEST_CODE_AUTH_REAL_SHOT)
    }

    fun createImageUri(): Uri? {
        val status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        return if (status.equals(Environment.MEDIA_MOUNTED)) {
            contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, ContentValues());
        } else {
            contentResolver.insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, ContentValues());
        }
    }

}